package br.com.travesso.security.authentication;

import java.security.Principal;
import java.security.cert.X509Certificate;
import java.sql.SQLException;
import java.util.Properties;

import br.com.travesso.security.dao.DBHelper;
import br.com.travesso.security.dao.UsuarioDAO;
import br.com.travesso.security.domain.Usuario;
import br.com.travesso.security.util.ConfigConstants;
import br.com.travesso.util.Criptografia;
import br.gov.component.demoiselle.security.auth.provider.IAuthenticationProvider;
import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer;
import br.gov.frameworkdemoiselle.util.ResourceBundle;

public class AuthenticationProvider implements IAuthenticationProvider {

	private ResourceBundle bundle = ResourceBundleProducer
			.create("EdpSecurityMessages");

	private DBHelper dbHelper;

	private UsuarioDAO usuarioDAO;

	public void initialize(Properties properties) {
		this.dbHelper = new DBHelper(properties.getProperty(
				ConfigConstants.CONFIG_KEY_DB_JNDI_NAME, null));
		this.usuarioDAO = new UsuarioDAO(dbHelper);
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		dbHelper.closeConnection();
	}

	@Override
	public Principal authenticate(String loginInformado, String senhaInformada) {

		Usuario user;

		try {
			user = usuarioDAO.buscarPorLogin(loginInformado);
		} catch (SQLException e) {
			throw new SecurityException(
					bundle.getString("erro.consulta.banco.de.dados"));
		}

		if (user == null) {
			throw new SecurityException(
					bundle.getString("usuario.nao.cadastrado"));
		}

		if (!Criptografia.sha256(senhaInformada).equals(user.getSenha())) {
			throw new SecurityException(
					bundle.getString("usuario.senha.incorreta"));
		}

		final UserPrincipal userPrincipal = new UserPrincipal();
		userPrincipal.setId(user.getId());
		userPrincipal.setLoginInformado(user.getLogin());
		return userPrincipal;

	}

	@Override
	public Principal authenticate(String user, String password,
			String newPassword) {
		throw new UnsupportedOperationException(
				"Troca de senha não implementada.");
	}

	@Override
	public Principal authenticate(X509Certificate x509) {
		throw new UnsupportedOperationException(
				"Autenticação por certificado digital não implementada.");
	}

}
